package com.zb.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zb.common.exception.BusinessException;
import com.zb.common.mapper.DownLoadMapper;
import com.zb.common.mapper.RoleMapper;
import com.zb.common.mapper.UserMapper;
import com.zb.common.po.config.ConfigInfo;
import com.zb.common.po.enums.PageSize;
import com.zb.common.po.enums.UserStatus;
import com.zb.common.po.model.DownLoad;
import com.zb.common.po.model.Role;
import com.zb.common.po.model.User;
import com.zb.common.po.query.UserQuery;
import com.zb.common.utils.PaginationResult;
import com.zb.common.utils.SimplePage;
import com.zb.common.utils.StringUtil;
import com.zb.service.MenuService;
import com.zb.service.UserService;

@Service(value = "userService")
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory
            .getLogger(UserServiceImpl.class);

    @Resource
    private ConfigInfo configInfo;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private MenuService menuService;

    @Resource
    private DownLoadMapper downLoadMapper;

    @Override
    public User login(String account, String password) throws BusinessException {
        if (StringUtil.isEmpty(account) || StringUtil.isEmpty(password)) {
            throw new BusinessException("账号密码不能为空");
        }
        UserQuery query = new UserQuery();
        query.setAccount(account);
        query.setUserStatus(UserStatus.NORMAL);
        User user = this.getUserByAccount(account, UserStatus.NORMAL, true);
        if (user.getPassword().equals(StringUtil.encodeByMD5(password))) {
            return user;
        } else {
            throw new BusinessException("账号或密码错误");
        }
    }

    @Override
    public int findUsersCount(UserQuery query) throws BusinessException {
        try {
            return this.userMapper.selectUserCount(query);
        } catch (Exception e) {
            logger.info("查询数据库异常", e);
            throw new BusinessException(e.getMessage());
        }

    }

    @Override
    public PaginationResult<User> findUsersByPage(UserQuery query)
            throws BusinessException {
        try {
            int count = this.userMapper.selectUserCount(query);
            int pageSize = query.getPageSize() == null ? PageSize.SIZE20
                    .getSize() : query.getPageSize();
            int pageNo = 0;
            if (null != query.getPageNo()) {
                pageNo = query.getPageNo();
            }
            SimplePage page = new SimplePage(pageNo, count, pageSize);
            query.setPage(page);
            List<User> list = this.userMapper.selectUserList(query);
            for (User user : list) {
                if (!user.getRoles().isEmpty()) {
                    List<Role> roleList = roleMapper.selectRolesByRoleIds(user
                            .getRoles());
                    StringBuilder sb = new StringBuilder();
                    for (Role role : roleList) {
                        sb.append(role.getRoleName() + ",");
                    }
                    if (!StringUtils.isEmpty(sb.toString())) {
                        user.setRoleName(sb.toString().substring(0,
                                sb.length() - 1));
                    } else {
                        user.setRoleName("");
                    }
                }
            }
            PaginationResult<User> result = new PaginationResult<User>(page,
                    list);
            return result;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    @Override
    public User findUserByUserId(String userId) throws BusinessException {
        UserQuery query = new UserQuery();
        query.setUserId(userId);
        User user = this.getUserByUserId(userId, UserStatus.NORMAL, false);
        if (!user.getRoles().isEmpty()) {
            List<Role> roleList = roleMapper.selectRolesByRoleIds(user
                    .getRoles());
            StringBuilder sb = new StringBuilder();

            List<String> roles = new ArrayList<String>();
            user.setRoles(roles);
            for (Role role : roleList) {
                roles.add(String.valueOf(role.getId()));
                sb.append(role.getRoleName() + ",");
            }
            if (!StringUtils.isEmpty(sb.toString())) {
                user.setRoleName(sb.toString().substring(0, sb.length() - 1));
            } else {
                user.setRoleName("");
            }
        }
        return user;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveUser(User user) throws BusinessException {
        user.setPassword(StringUtil.encodeByMD5(user.getPassword()));
        if (StringUtils.isEmpty(user.getRole())
                || StringUtils.isEmpty(user.getUserName())
                || StringUtils.isEmpty(user.getAccount())) {
            throw new BusinessException("参数错误");
        }
        if (StringUtils.isEmpty(user.getUserId())) {
            user.setCreateTime(new Date());
            this.userMapper.inserUser(user);
            // 设置下载情况
            DownLoad downLoad = new DownLoad();
            downLoad.setUserId(user.getUserId());
            downLoadMapper.inserDownLoad(downLoad);
        } else {
            // 修改用户的时候不修改密码
            user.setPassword(null);
            this.userMapper.updateUser(user);
        }
        UserQuery query = new UserQuery();
        query.setAccount(user.getAccount());
        List<User> userList = userMapper.selectUserList(query);
        // 判断角色重名
        if (userList.size() > 1) {
            throw new BusinessException("账号已经存在！");
        }
    }

    @Override
    public void updateUserStatus(Integer[] userIds, UserStatus userStatus)
            throws BusinessException {
        if (null == userIds || userIds.length == 0 || null == userStatus) {
            throw new BusinessException("参数错误");
        }
        userMapper.updateUserStatus(userIds, userStatus);
    }

    @Override
    public void delteUser(Integer[] userIds) throws BusinessException {
        if (null == userIds || userIds.length == 0) {
            throw new BusinessException("参数错误");
        }

        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < userIds.length; i++) {
            if (userIds[i] > 1001) {
                list.add(userIds[i]);
            }
        }
        Integer[] newStr = list.toArray(new Integer[1]);

        // 结束
        userMapper.deleteUser(newStr);
    }

    @Override
    public void updateUserSelf(String oldPwd, User user)
            throws BusinessException {
        // 演示账号，直接返回，不可以需改账户信息
        final String testUserId = "1013";
        if (testUserId.equals(user.getUserId())) {
            return;
        }
        UserQuery query = new UserQuery();
        query.setUserId(user.getUserId());
        query.setUserStatus(UserStatus.NORMAL);
        User tempUser = this.getUserByUserId(user.getUserId(),
                UserStatus.NORMAL, true);
        if (!StringUtils.isEmpty(user.getPassword())) {// 新密码不为空
            if (tempUser.getPassword().equals(StringUtil.encodeByMD5(oldPwd))) {
                user.setPassword(StringUtil.encodeByMD5(user.getPassword()));
            } else {
                throw new BusinessException("原密码错误");
            }
        }
        userMapper.updateUser(user);
    }

    @Override
    public User getUserByUserId(String userId, UserStatus userStatus,
            boolean whithPwd) throws BusinessException {
        UserQuery query = new UserQuery();
        query.setUserId(userId);
        query.setUserStatus(userStatus);
        List<User> userList = this.userMapper.selectUserListWidthPwd(query);
        if (userList.size() != 1) {
            throw new BusinessException("用户不存在");
        }
        User user = userList.get(0);
        if (!whithPwd) {
            user.setPassword("");
        }
        return user;
    }

    @Override
    public User getUserByAccount(String account, UserStatus userStatus,
            boolean whithPwd) throws BusinessException {
        UserQuery query = new UserQuery();
        query.setAccount(account);
        query.setUserStatus(userStatus);
        List<User> userList = this.userMapper.selectUserListWidthPwd(query);
        if (userList.size() != 1) {
            throw new BusinessException("用户不存在");
        }
        User user = userList.get(0);
        if (!whithPwd) {
            user.setPassword("");
        }
        return user;
    }

}
